import Vue 				from 'vue'
import util 			from '../../util'
import axios 			from 'axios'
import { List,Toast } 	from 'vant'
Vue.use(List,Toast)

export default {
	name: 'orderList',
	data(){
		return {
			pageState:1,		//1:购买订单   2:出售订单
			pageIndex:1,		//页数
			list:[],
			loading:false,
			finished:false,
			loadError:false,
			offset:200,
		}
	},
	computed:{
		topDistance(){
			//容器与顶部距离
			let clientWidth = document.documentElement.clientWidth;
			let _rem = clientWidth >= 750 ? 100 : 100 * (clientWidth / 750);
			return 'top:'+(0.5*_rem+100)+'px';
		},
	},
	methods:{
		load(){
			this.loading = true;
			setTimeout(()=>{
				let _url = this.pageState == 1?'/otc/inmoney-list':'/otc/outmoney-list'
				util.fetch(util.ajaxUrl+_url,{
					page:this.pageIndex,
					intype:''
				}).then(res => {
					this.loading = false;
					if(res.retCode === 0){
						//修改时间格式
						res.retData.list.map(item => {
							item.date = util.transTime(item.create_time);
							if(this.pageState == 1){
								//购买订单状态
								switch(item.state){
									case('-99'):
										item.showState = '已取消';
										break;
									case('1'):
										item.showState = '待付款';
										item.leftSec   = item.left_time;
										item.showTimer = '';
										break;
									case('2'):
										// item.showState = '处理中';
										item.showState = '已付款';
										break;
									case('3'):
										item.showState = '已完成';
										break;
									case('4'):
										// item.showState = '处理中';
										item.showState = '已付款';
									case('99'):
										item.showState = '已取消';
										break;
									default:
										item.showState = '未知状态'
								}
							}else if(this.pageState == 2){
								//出售状态
								switch(item.state){
									case('99'):
										item.showState = '已完成';
										break;
									case('-1'):
										item.showState = '已完成';
										break;
									case('-2'):
										// item.showState = '处理中';
										item.showState = '对方付款中';
										break;
									case('-3'):
										// item.showState = '已驳回';
										item.showState = '已取消';
										break;
									case('-4'):
										// item.showState = '处理中';
										item.showState = '对方付款中';
										break;
									case('-5'):
										item.showState = '待转币';
										item.leftSec = item.lefttime;
										item.showTimer = '';
										break;
									case('-99'):
										item.showState = '已取消';
										break;
									default:
										item.showState = '未知状态'
								}
							}
						})
						this.list = this.list.concat(res.retData.list);
						if(!res.retData || res.retData.list && res.retData.list.length < 20){
							this.finished = true;
						}
					}else{
						this.loadError = true;
						Toast(res.retMsg || '未知错误')
					}
				}).catch(error => {
					this.loading = false;
					this.loadError = true;
				}).finally(e => {
					this.pageIndex++;
				})
			},500)
		},
		timer(){
			//可能的倒计时
			let _filter = this.list.filter(item => (item.state == 1 || item.state == -5));
			if(_filter.length > 0){
				this.list.map((item,index) => {
					if(item.leftSec && item.leftSec > 0){
						item.leftSec--
						let mins    = Math.floor(item.leftSec/60);          //分钟
		                let seconds = item.leftSec - mins*60;               //秒
		                //确保时分秒都是2位数
		                mins        = mins.toString().length==1?'0'+mins:mins;
		                seconds     = seconds.toString().length==1?'0'+seconds:seconds;
		                item.showTimer = mins+':'+seconds;
					}
					if(item.leftSec <= 0 && (item.state == 1 || item.state == -5)){
						//倒计时结束
						item.state = '-99';
						item.showState = '已取消';
						this.$set(this.list,index,item);
					}
				})
			}
			setTimeout(this.timer,1000)
		},
		checkoutTimer(){
			//校验可能存在的倒计时问题
			let find = this.list.find(item => item.state == 1);
			if(find){
				util.fetch(util.ajaxUrl + '/otc/inmoney-detail',{
					id:find.id
				}).then(res => {
					if(res.retCode === 0){
						find.leftSec = res.retData.left_time
					}else{
						
					}
				}).catch(error => {
				})
			}
			setTimeout(this.checkoutTimer,8000)
		},
		goPay(_item){
			let query = {
				orderId:_item.id,
				from:'orderList',
				death:1
			}
			if(this.pageState == 1){
				query.noSession = 1;
			}else{
				query.isSell = 1;
			}
			this.$router.push({
				path:'/makeOrder',
				query:query
			})
		},
		changeState(state){
			if(this.loading) return
			this.pageIndex = 1;
			this.list = [];
			this.pageState = state;
			this.finished = false;
			this.loading = true;
			this.load();
		},
		goDetail(_item){
			if(this.pageState == 1 && _item.state == 1){
				//跳转到付款页面
				this.goPay(_item);
				return
			}
			if(this.pageState == 2 && _item.state == -5){
				//跳转到付款页面
				this.goPay(_item);
				return
			}
			this.$router.push({
				path:'/orderDetail',
				query:{
					id:_item.id,
					pageState:this.pageState
				}
			})
		},
		goBack(){
			util.navigateBack(-1,this)
		},
		refreshItem(orderId){
			//若从付款页面过来，则试着刷新状态
			let _url = util.ajaxUrl + (this.pageState == 1?'/otc/inmoney-detail':'/otc/outmoney-detail');
			util.fetch(_url,{
				token:util.getToken(),
				id:orderId
			}).then(res => {
				if(res.retCode === 0){
					this.list.forEach((item,index) => {
						if(item.id == orderId) {
							//强制更新当前状态
							item.state = res.retData.state;
							this.$set(this.list,index,item);
							localStorage.removeItem('orderId');
						}
					})
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		}
	},
	created() {
		if(this.$route.query.pageState) this.pageState = this.$route.query.pageState;
		let sessionPageState = sessionStorage.getItem('pageState')
		if(sessionPageState){
			this.pageState = sessionPageState;
			sessionStorage.removeItem('pageState')
		}
		util.waitSDKReady().then(token => {
			this.token = token;
		}).catch((e) => {
			console.log('获取token失败')
		})
		this.timer();
		this.checkoutTimer();
		setTimeout(()=>{
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				let orderId = util.getStorage('orderId');
				if(orderId && this.list.length > 0){
					this.refreshItem(orderId)
				}
			})
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				this.token = '';
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
		},500)
    }
}